import React from 'react'
import { connect } from 'react-redux'
import { projectLabelView as projectLabelViewDuck, global as globalDuck } from 'ducks'
import { Query } from 'react-apollo'
import getPageInfo from 'graphql/getTaskPageInfo.graphql'
import FetchItemPage from './fetchItemPage'

const pageInfo = ({
  pid, user, state, actionRecivePageInfo, total,
}) => (
  <Query
    query={getPageInfo}
    variables={{ projectId: pid, userId: user.id, state }}
    fetchPolicy="network-only"
    onCompleted={data => actionRecivePageInfo(data.project_task_item_aggregate.aggregate.count)}
  >
    {({ loading, error, data }) => {
      if (loading) return 'loading...'
      if (error) return `Error! ${error.message}`
      if (total !== undefined) {
        return <FetchItemPage pid={pid} />
      }
      return null
    }}
  </Query>
)

const mapStateToProps = state => ({
  state: projectLabelViewDuck.selectors.pageInfo(state).state,
  total: projectLabelViewDuck.selectors.pageInfo(state).total,
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  actionRecivePageInfo: projectLabelViewDuck.creators.actionRecivePageInfo,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(pageInfo)
